<template>
  <div class="pay">
    <van-nav-bar
      title="订单结算"
      left-text="返回"
      @click-left="back"
      left-arrow
    />
    <div class="address-card">
      <div class="add-select">
        <div class="add-title" @click="showAddressList">选择地址</div>
        <van-icon name="arrow" />
      </div>
      <div class="user-msg">
        <div class="username">{{ address.name }}</div>
        <div class="phone">{{ address.tel }}</div>
        <div class="default" v-show="address.isDefault">默认</div>
      </div>
      <div class="address">{{ address.address }}</div>
    </div>
    <div class="pay-info">
      <div style="background: #fff">
        <PayBox :countAndPrice="countAndPrice">
          <template #pay-item>
            <PayItem
              v-for="item in shopCarData"
              :key="item.sid"
              :item="item"
            ></PayItem>
          </template>
        </PayBox>
      </div>
    </div>

    <van-popup v-model="show" position="bottom">
      <van-address-list
        v-model="addressId"
        :list="list"
        default-tag-text="默认"
        @select="selectAddress"
        @add="addAddress"
      />
    </van-popup>

    <!-- 立即结算 -->
    <div class="payBtn">
      <van-button type="primary" color="#307dd5" round block @click="pay"
        >立即结算</van-button
      >
    </div>
  </div>
</template>

<script>
import PayBox from "../components/PayBox";
import PayItem from "../components/PayItem";
import "../assets/less/pay.less";
import { mapState, mapMutations } from "vuex";
export default {
  name: "Pay",
  components: {
    PayBox,
    PayItem,
  },
  data() {
    return {
      sid: [],
      list: [],
      addressId: "",
      address: {},
      shopCarData: [],
      countAndPrice: {
        count: 0,
        total: 0,
      },
      show: false,
    };
  },
  created() {
    this.sid = this.$route.query.sids.split("-");
    console.log(this.sid);
    this.getAddressList();
    this.getCarByPay();
  },

  computed: {
    ...mapState(["shopCarCount"]),
  },

  methods: {
    ...mapMutations(["changeShopCarCount"]),

    back() {
      this.$router.back();
    },

    showAddressList() {
      this.show = true;
    },

    addAddress() {
      this.$router.push({ name: "Address" });
    },

    // 选择地址
    selectAddress(v) {
      this.addressId = v.id;
      this.address = { ...v };
      this.show = false;
    },

    // 查询用户地址
    getAddressList() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "GET",
        url: this.baseURL + "/findAddress",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 20000) {
            response.data.result.forEach((v) => {
              v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`;
              v.isDefault = !!v.isDefault;
              if (v.isDefault) {
                this.addressId = v.id;
                this.address = { ...v };
              }
            });
            this.list = response.data.result;
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 获取提交订单的购物车商品
    getCarByPay() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "GET",
        url: this.baseURL + "/commitShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(this.sid),
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code == 50000) {
            if (response.data.result.length == 0) {
              this.$router.push({ path: "/" });
            }

            response.data.result.forEach((v) => {
              this.countAndPrice.count += v.count;
              this.countAndPrice.total += v.count * v.price;
            });
            this.shopCarData = response.data.result;
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 结算订单
    pay() {
      if (!this.address.aid) {
        return this.$toast({
          message: "选择收货地址",
          forbidClick: true,
          duration: 2000,
        });
      }

      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      let data = {
        appkey: this.appkey,
        tokenString,
        sids: JSON.stringify(this.sid),
        phone: this.address.tel,
        address: this.address.address,
        receiver: this.address.name,
      };

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseURL + "/pay",
        data,
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code == 60000) {
            this.changeShopCarCount(this.shopCarCount - this.sid.length);
            this.$router.push({ name: "Order" });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },
  },
};
</script>
